(function($) {
	$.alerts = {
		obj1 : "",
		obj2 : "",
		/**
		 * 
		 * @param {Object} obj1	每个商品的总价
		 * @param {Object} obj2 所有商品的总价
		 */
		setTotalprice : function (obj1, obj2) {
			$.alerts.obj1 = obj1;
			$.alerts.obj2 = obj2;
		},
		bindClick : function(opts) {
			opts = jQuery.extend({
				add : "",//增加按钮
				reduce : "",//减少按钮
				qty_item : "",//商品数量输入框
				total : "",//该商品总价标签
				price : 0//该商品价格
			}, opts || {});
			
		    var min = 1;
		    var max = 999;
		    reg = function(x) {
		        return new RegExp("^[1-9]\\d*$").test(x);
		    }
		    amount = function(obj, mode) {
		        var x = $(obj).val();
		        if (reg(x)) {
		            if (mode) {
		                x++;
		            } else {
		                x--;
		            }
		        } else {
		            alert("请输入正确的数量！");
		            $(obj).val(1);
		            $(obj).focus();
		        }
		        return x;
		    }
		    reduce = function(obj) {
		        var x = this.amount(obj, false);
		        if (x >= this.min) {
		            $(obj).val(x);
		            recalc();
		        } else {
		            alert("商品数量最少为" + this.min);
		            $(obj).val(1);
		            $(obj).focus();
		        }
		    }
		    recalc = function(x, price, obj) {
		    	obj.html(parseFloat(price * x).toFixed(2));
		    	var tal = 0;
		    	$.alerts.obj1.each(function() {
		    		var v = parseFloat($(this).html());
		    		tal += v;
		    	});
		    	$.alerts.obj2.html(parseFloat(tal).toFixed(2));
		    }
			$(opts.add).click(function() {
				var x = amount(opts.qty_item, true);
				if (reg(x)) {
					if (x <= max) {
			            opts.qty_item.val(x);
			            recalc(x, opts.price, opts.total);
			        } else {
			            alert("商品数量最多为" + max);
			            opts.qty_item.val(max);
			            opts.qty_item.focus();
			            recalc(max, opts.price, opts.total);
			        }
				}
			});
			$(opts.reduce).click(function() {
				var x = amount(opts.qty_item, false);
				if (reg(x)) {
					if (x >= min) {
			            opts.qty_item.val(x);
			            recalc(x, opts.price, opts.total);
			        } else {
			            alert("商品数量最少为" + min);
			            opts.qty_item.val(1);
			            opts.qty_item.focus();
			            recalc(min, opts.price, opts.total);
			        }
				}
			});
		}
	}
})(jQuery);
